package com.dms.wuziqi.fliter;

import com.dms.wuziqi.JwtUtil.JwtUtil2;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.Map;
@Component
public class RoleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器启动");
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod= (HandlerMethod) handler;
            Method method=handlerMethod.getMethod();
            if (method.isAnnotationPresent(Role.class)){
                Role roleAnnotation=method.getAnnotation(Role.class);
                String requireRole=roleAnnotation.role();
                String token=request.getHeader("Authorization");
                if (token==null){

                    response.sendError(0,"错误");
                    System.out.println("没有token");
                    return false;
                }
                Map<String,Object> claims=JwtUtil2.parseToken(token);
                String userRole= (String) claims.get("role");
                if (!userRole.equals(requireRole)){
                    System.out.println("角色不正确");
                    response.sendError(1,"角色不正确");
                    return false;
                }
            }
        }
        return true;
    }
}
